package com.cuit.zuke.system.controller;

import com.cuit.zuke.common.annotation.ControllerEndpoint;
import com.cuit.zuke.common.util.Result;
import com.cuit.zuke.common.vo.PasswordForm;
import com.cuit.zuke.system.entity.SysAdminEntity;
import com.cuit.zuke.system.entity.SysDepartmentEntity;
import com.cuit.zuke.system.entity.SysRoleEntity;
import com.cuit.zuke.system.entity.vo.LoginLogVO;
import com.cuit.zuke.system.service.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @program: zuke
 * @description: 管理员
 * @author: KamTang
 * @create: 2022-04-01 18:46
 **/
@RestController
@RequestMapping("/sys/admin")
public class SysAdminController extends SysAdminAbstractController {


    @Autowired
    private SysAdminService adminService;

    @Autowired
    private SysLoginLogService loginLogService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysDepartmentService departmentService;

    @Autowired
    private SysAdminRoleService adminRoleService;


    @GetMapping("/list")
    public Result list (@RequestParam Map<String, Object> params) {
        return Result.ok().put("page", adminService.queryAdmin(params));
        //return Result.ok().put("page", adminService.queryPage(params));
    }

    /**
     * 获取登录的管理员信息
     */
    @GetMapping("/info")
    public Result info(){
        LoginLogVO loginLogVO = loginLogService.getLastLoginInfo(getAdmin().getUsername()).get(0);
        List<SysRoleEntity> roleInfoByUserId = roleService.getRoleInfoByUserId(getAdmin().getUserId());
        SysDepartmentEntity department = departmentService.getById(getAdmin().getDepartmentId());
        SysAdminEntity sysAdmin = getAdmin();
        sysAdmin.setRoles(roleInfoByUserId);
        sysAdmin.setLoginTime(loginLogVO.getLoginTime());
        sysAdmin.setLocation(loginLogVO.getLocation());
        sysAdmin.setIp(loginLogVO.getIp());
        sysAdmin.setRoles(roleInfoByUserId);
        sysAdmin.setRoleIdList(adminRoleService.queryRoleIdList(sysAdmin.getUserId()));
        sysAdmin.setDepartment(department.getName());
        return Result.ok().put("admin", getAdmin());
    }

    /**
     * 根据id获取管理员信息
     * @param userId
     * @return
     */
    @GetMapping("/info/{userId}")
    public Result getInfoById (@PathVariable("userId") Long userId) {
        return Result.ok().put("admin", adminService.getById(userId));
    }

    /**
     * 删除管理员
     * @param ids id
     * @return Result
     */
    @ControllerEndpoint(exceptionMessage = "管理员删除失败", operation = "删除管理员")
    @RequiresPermissions("sys:admin:delete")
    @PostMapping("/delete")
    public Result deleteBatch (@RequestBody Long[] ids) {
        // 系统管理员不能删除
        if (ArrayUtils.contains(ids, 1L)) {
            return Result.error("系统管理员不能删除");
        }
        // 当前登录用户不能删除
        if (ArrayUtils.contains(ids, getAdmin().getUserId())) {
            return Result.error("当前用户不能被删除");
        }
        boolean flag = adminService.removeByIds(Arrays.asList(ids));
        if (flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 修改密码
     * @param passwordForm
     * @return
     */
    @PostMapping("/updatePwd")
    public Result updatePwd (@RequestBody PasswordForm passwordForm) {
        // 由于前端有数据校验，这里不需要对PasswordForm进行非空判断
        //sha256加密
        String password = new Sha256Hash(passwordForm.getPassword(), getAdmin().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(passwordForm.getNewPassword(), getAdmin().getSalt()).toHex();

        boolean flag = adminService.updatePwd(getAdmin().getUserId(), password, newPassword);
        if (!flag) {
            return Result.error("原密码不正确");
        }
        return Result.ok();
    }

    /**
     * 新增管理员
     */
    @ControllerEndpoint(exceptionMessage = "管理员添加失败", operation = "添加管理员")
    @PostMapping("/save")
    @RequiresPermissions("sys:admin:save")
    public Result save(@RequestBody SysAdminEntity admin){
        adminService.saveUser(admin);
        return Result.ok();
    }

    /**
     * 修改管理员信息
     */
    @PostMapping("/update")
    @RequiresPermissions("sys:admin:update")
    public Result update(@RequestBody SysAdminEntity admin){
        adminService.update(admin);
        return Result.ok();
    }

}
